package org.abc.fund.config.ScheduleUpdateConfig;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.abc.fund.service.dataSourceCollection.BatchDataCollectionService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * 基金数据定时更新配置
 */
@Configuration
@EnableScheduling
@RequiredArgsConstructor
@Slf4j
public class FundDataSchedulingConfig {

    private final BatchDataCollectionService batchCollectionService;
    
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /**
     * 每日更新任务：基金净值、融资融券、货币基金收益
     * 每天18:00执行（市场收盘后）
     */
    @Scheduled(cron = "0 0 18 * * MON-FRI")
    @ConditionalOnProperty(name = "fund.data.scheduling.daily.enabled", havingValue = "true", matchIfMissing = true)
    public void dailyUpdate() {
        log.info("开始执行每日数据更新任务...");
        
        BatchDataCollectionService.BatchCollectionConfig config = new BatchDataCollectionService.BatchCollectionConfig();
        config.setMode(BatchDataCollectionService.BatchMode.AUTO_UPDATE);
        config.setStrategy(BatchDataCollectionService.CollectionStrategy.INCREMENTAL);
        config.setConcurrent(true);
        config.setBatchSize(20);
        config.setDeleteOldBeforeInsert(true);
        
        // 设置数据类型
        config.setDataTypes(Arrays.asList(
            "FUND_NET_VALUE", 
            "FUND_MTSS", 
            "FUND_MF_DAILY_PROFIT"
        ));
        
        // 设置时间范围为最近30天（防止遗漏）
        BatchDataCollectionService.DateRangeConfig dateRange = new BatchDataCollectionService.DateRangeConfig();
        dateRange.setStartDate(LocalDate.now().minusDays(30).format(DATE_FORMATTER));
        dateRange.setEndDate(LocalDate.now().format(DATE_FORMATTER));
        config.setDateRange(dateRange);
        
        try {
            BatchDataCollectionService.BatchCollectionResult result = 
                batchCollectionService.executeBatchCollection(config);
            
            log.info("每日数据更新完成: 成功 {} 只基金, 失败 {} 只基金", 
                    result.getSuccessCount(), result.getFailureCount());
                    
            // 记录各数据类型统计
            result.getDataTypeStats().forEach((dataType, count) -> {
                log.info("数据类型 {}: 更新 {} 条记录", dataType, count);
            });
            
        } catch (Exception e) {
            log.error("每日数据更新任务执行失败", e);
        }
    }

    /**
     * 每周更新任务：财务指标
     * 每周日20:00执行
     */
    @Scheduled(cron = "0 0 20 * * SUN")
    @ConditionalOnProperty(name = "fund.data.scheduling.weekly.enabled", havingValue = "true", matchIfMissing = true)
    public void weeklyUpdate() {
        log.info("开始执行每周数据更新任务...");
        
        BatchDataCollectionService.BatchCollectionConfig config = new BatchDataCollectionService.BatchCollectionConfig();
        config.setMode(BatchDataCollectionService.BatchMode.AUTO_UPDATE);
        config.setStrategy(BatchDataCollectionService.CollectionStrategy.INCREMENTAL);
        config.setConcurrent(true);
        config.setBatchSize(15);
        config.setDeleteOldBeforeInsert(false); // 财务指标不需要删除，通常不会重复
        
        config.setDataTypes(List.of("FUND_FIN_INDICATOR"));
        
        // 设置时间范围为最近3个月
        BatchDataCollectionService.DateRangeConfig dateRange = new BatchDataCollectionService.DateRangeConfig();
        dateRange.setStartDate(LocalDate.now().minusMonths(3).format(DATE_FORMATTER));
        dateRange.setEndDate(LocalDate.now().format(DATE_FORMATTER));
        config.setDateRange(dateRange);
        
        try {
            BatchDataCollectionService.BatchCollectionResult result = 
                batchCollectionService.executeBatchCollection(config);
            
            log.info("每周数据更新完成: 成功 {} 只基金, 失败 {} 只基金", 
                    result.getSuccessCount(), result.getFailureCount());
                    
        } catch (Exception e) {
            log.error("每周数据更新任务执行失败", e);
        }
    }

    /**
     * 每月更新任务：基金分红
     * 每月1号22:00执行
     */
    @Scheduled(cron = "0 0 22 1 * ?")
    @ConditionalOnProperty(name = "fund.data.scheduling.monthly.enabled", havingValue = "true", matchIfMissing = true)
    public void monthlyUpdate() {
        log.info("开始执行每月数据更新任务...");
        
        BatchDataCollectionService.BatchCollectionConfig config = new BatchDataCollectionService.BatchCollectionConfig();
        config.setMode(BatchDataCollectionService.BatchMode.AUTO_UPDATE);
        config.setStrategy(BatchDataCollectionService.CollectionStrategy.FULL_RANGE);
        config.setConcurrent(true);
        config.setBatchSize(10);
        config.setDeleteOldBeforeInsert(true); // 全量更新需要删除旧数据
        
        config.setDataTypes(List.of("FUND_DIVIDEND"));
        
        // 设置时间范围为最近6个月
        BatchDataCollectionService.DateRangeConfig dateRange = new BatchDataCollectionService.DateRangeConfig();
        dateRange.setStartDate(LocalDate.now().minusMonths(6).format(DATE_FORMATTER));
        dateRange.setEndDate(LocalDate.now().format(DATE_FORMATTER));
        config.setDateRange(dateRange);
        
        try {
            BatchDataCollectionService.BatchCollectionResult result = 
                batchCollectionService.executeBatchCollection(config);
            
            log.info("每月数据更新完成: 成功 {} 只基金, 失败 {} 只基金", 
                    result.getSuccessCount(), result.getFailureCount());
                    
        } catch (Exception e) {
            log.error("每月数据更新任务执行失败", e);
        }
    }

    /**
     * 手动触发全量更新接口（用于特殊情况）
     */
    public BatchDataCollectionService.BatchCollectionResult triggerManualUpdate(
            List<String> dataTypes, 
            String startDate, 
            String endDate) {
        
        log.info("手动触发全量数据更新: 数据类型 {}, 时间范围 {} 到 {}", 
                dataTypes, startDate, endDate);
        
        BatchDataCollectionService.BatchCollectionConfig config = new BatchDataCollectionService.BatchCollectionConfig();
        config.setMode(BatchDataCollectionService.BatchMode.MANUAL_UPDATE);
        config.setStrategy(BatchDataCollectionService.CollectionStrategy.FULL_RANGE);
        config.setConcurrent(true);
        config.setBatchSize(10);
        config.setDeleteOldBeforeInsert(true);
        config.setDataTypes(dataTypes);
        
        BatchDataCollectionService.DateRangeConfig dateRange = new BatchDataCollectionService.DateRangeConfig();
        dateRange.setStartDate(startDate);
        dateRange.setEndDate(endDate);
        config.setDateRange(dateRange);
        
        return batchCollectionService.executeBatchCollection(config);
    }
}